package com.cloud.manage.utils;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;


/**
 * 工具
 * Tools.java
 *
 * @author zhangHongWei
 * @date 2018-6-6 下午4:05:03
 */
public class Tools {
    public static String formatTime(String pubTime) {
        DateTime parse = DateUtil.parse(pubTime + "00");
        return DateUtil.format(DateUtil.offsetHour(parse, 8), "yyyyMMddHHmm");
    }
    //删除目录下文件
    public static void deleteFile(int size, String saveFilePath) {
        File directory = new File(saveFilePath);

        // 获取所有的目录
        File[] directories = directory.listFiles(File::isDirectory);

        if (directories == null || size >= directories.length) {
            return; // 如果没有目录，或者目录数量小于或等于指定的 size，直接返回
        }

        // 只关心需要删除的目录，避免对所有目录进行排序
        int directoriesToDeleteCount = directories.length - size;

        // 创建一个基于 lastModified 时间戳的优先队列（最小堆），
        // 优先删除最近修改的文件，而非对所有文件排序
        PriorityQueue<File> oldestDirs = new PriorityQueue<>(directoriesToDeleteCount,
                Comparator.comparingLong(File::lastModified)); // 最旧的排在前面

        // 将所有目录加入堆中
        for (File dir : directories) {
            if (oldestDirs.size() < directoriesToDeleteCount) {
                oldestDirs.offer(dir);  // 如果堆还没有达到需要删除的目录数，加入堆
            } else if (dir.lastModified() < oldestDirs.peek().lastModified()) {
                oldestDirs.poll(); // 移除最旧的目录
                oldestDirs.offer(dir); // 加入当前目录
            }
        }

        // 删除堆中所有的目录
        while (!oldestDirs.isEmpty()) {
            deleteDirectory(oldestDirs.poll());
        }
    }

    // 递归删除目录及其内部的所有文件和子目录
    public static void deleteDirectory(File file) {
        if (file.isDirectory()) {
            File[] entries = file.listFiles();
            if (entries != null) {
                for (File entry : entries) {
                    deleteDirectory(entry);
                }
            }
        }
        // 尝试删除目录或文件
        if (!file.delete()) {
            System.err.println("Failed to delete " + file);
        }
    }
    public static String yubao(String urlIp, String type, String name, String starttime, ClzJobUnit jobUnit) {

        String endtime = DateUtil.format(new Date(), "yyyyMMddHHmm");

        String url = null;
        if (type.equals("fileName")) {
            url = "http://" + urlIp + "/services/api/meteodata/data?userId=wanyungongsi&pwd=Wygs1234878&interfaceId=sevpFileInfosearch&dataCode=sevp&elements=" + name + "&makestarttime=" + starttime + "&makeendtime=" + endtime + "&latestSize=10";
        }
        if (type.equals("name")) {
            url = "http://" + urlIp + "/services/api/meteodata/data?userId=wanyungongsi&pwd=Wygs1234878&interfaceId=sevpGetFile&productid=" + name + "&showtype=file";
        }

        String responseStr = "";
        for (int i = 0; i < 5; i++) {
            try {
                responseStr = HttpUtil.get(url, 10 * 1000);
                if (StrUtil.isNotBlank(responseStr)) {
                    break;
                }
            } catch (Exception e) {
                jobUnit.jobErrorInfo(e);
            }
        }
        return responseStr;
    }

    public static String yubao_fs(String typeName, ClzJobUnit jobUnit) {

        String endtime = DateUtil.format(new Date(), "yyyyMMddHHmm");

        String url = "http://10.225.25.136:8080/fsqxj/fs/zb/getLatestPdfNames?type=" + typeName + "&size=5";

        String responseStr = "";
        for (int i = 0; i < 5; i++) {
            try {
                responseStr = HttpUtil.get(url, 10 * 1000);
                if (StrUtil.isNotBlank(responseStr)) {
                    break;
                }
            } catch (Exception e) {
                jobUnit.jobErrorInfo(e);
            }
        }
        return responseStr;
    }


    //风力转换
    public static String fstrans(double fs) {
        double dataDouble = fs;
        String result;
        if (dataDouble < 0.3) {
            result = "0";
        } else if (dataDouble >= 0.3 && dataDouble <= 1.5) {
            result = "1";
        } else if (dataDouble < 3.4 && dataDouble > 1.5) {
            result = "2";
        } else if (dataDouble >= 3.4 && dataDouble < 5.5) {
            result = "3";
        } else if (dataDouble >= 5.5 && dataDouble < 8.0) {
            result = "4";
        } else if (dataDouble >= 8.0 && dataDouble < 10.8) {
            result = "5";
        } else if (dataDouble >= 10.8 && dataDouble < 13.9) {
            result = "6";
        } else if (dataDouble >= 13.9 && dataDouble < 17.2) {
            result = "7";
        } else if (dataDouble >= 17.2 && dataDouble < 20.8) {
            result = "8";
        } else if (dataDouble >= 20.8 && dataDouble < 24.5) {
            result = "9";
        } else if (dataDouble >= 24.5 && dataDouble < 28.5) {
            result = "10";
        } else if (dataDouble >= 28.5 && dataDouble < 32.7) {
            result = "11";
        } else {
            result = "12";
        }
        return String.valueOf(Double.parseDouble(result)+0.5);
        //return String.valueOf(Double.parseDouble(result));
    }

    public static String date2Strs(int i, String time) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        Date parse = sdf.parse(time);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(parse);
        calendar.add(calendar.MONTH, i);//把日期往后增加一天.整数往后推,负数往前移动
        parse = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter1 = new SimpleDateFormat("MM月");
        String dateString1 = formatter1.format(parse);
        return dateString1;
    }

    public static String date3Strs(int i, String datse) {
        Date date = str2Date(datse);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.HOUR, i);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(date);
        return dateString;
    }



    //将string 压缩加密
    public static String compressString(String uncompressed) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream)) {
            gzipOutputStream.write(uncompressed.getBytes(StandardCharsets.UTF_8));
        }
        return Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }

    /**
     * 计算文件大小
     *
     * @param size
     * @return
     */
    public static String FileSize(int size) {
        int GB = 1024 * 1024 * 1024;//定义GB的计算常量
        int MB = 1024 * 1024;//定义MB的计算常量
        int KB = 1024;//定义KB的计算常量
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
        String resultSize = "";
        if (size / GB >= 1) {
            //如果当前Byte的值大于等于1GB
            resultSize = df.format(size / (float) GB) + "GB";
        } else if (size / MB >= 1) {
            //如果当前Byte的值大于等于1MB
            resultSize = df.format(size / (float) MB) + "MB";
        } else if (size / KB >= 1) {
            //如果当前Byte的值大于等于1KB
            resultSize = df.format(size / (float) KB) + "KB";
        } else {
            resultSize = size + "B";
        }
        return resultSize;
    }

    /**
     * 把Blob类型转换为byte数组类型
     *
     * @param blob
     * @return
     */
    public static byte[] blobToBytes(Blob blob) {
        BufferedInputStream is = null;
        try {
            is = new BufferedInputStream(blob.getBinaryStream());
            byte[] bytes = new byte[(int) blob.length()];
            int len = bytes.length;
            int offset = 0;
            int read = 0;
            while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) {
                offset += read;
            }
            return bytes;
        } catch (Exception e) {
            return null;
        } finally {
            try {
                is.close();
                is = null;
            } catch (IOException e) {
                return null;
            }
        }
    }

    public static Date str3Date(String date) {
        if (notEmpty(date)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            try {
                return sdf.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return new Date();
        } else {
            return null;
        }
    }

    public static String date3Str(int i, String datse) {
        Date date = str3Date(datse);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, i);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String changeDay(int i) {
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, i);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String date1Str(Date date, int i) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, i);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat((calendar.get(Calendar.MONTH) + 1) + "月dd日00时-" + (calendar.get(Calendar.MONTH) + 1) + "月dd日24时;");
        String dateString = formatter.format(date);

        return dateString;
    }

    public static String dateHalfStr(Date date, int i) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, i);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat((calendar.get(Calendar.MONTH) + 1) + "月dd日00时-" + (calendar.get(Calendar.MONTH) + 1) + "月dd日12时;" + (calendar.get(Calendar.MONTH) + 1) + "月dd日12时-" + (calendar.get(Calendar.MONTH) + 1) + "月dd日24时;");
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String dateBymonth(int i, String datse) {
        Date date = str3Date(datse);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, i);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月");
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String get20Time(LocalDateTime now) {

        // 格式化器，用于将时间格式化为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        String timeStr = "";
        // 如果当前时间在20点之前，获取前一天的20点
        if (now.getHour() < 20 || (now.getHour() == 20 && now.getMinute() == 0)) {
            LocalDateTime yesterday20 = now.minusDays(1).withHour(20).withMinute(0).withSecond(0);
            timeStr = formatter.format(yesterday20);
        } else {
            // 如果当前时间在20点之后，获取当天的20点
            LocalDateTime today20 = now.withHour(20).withMinute(0).withSecond(0);
            timeStr = formatter.format(today20);
        }
        return timeStr;
    }

    /**
     * 随机生成六位数验证码
     *
     * @return
     */
    public static int getRandomNum() {
        Random r = new Random();
        return r.nextInt(900000) + 100000;
    }

    /**
     * 检测字符串是否不为空(null,"","null")
     *
     * @return 不为空则返回true，否则返回false
     */
    public static boolean notEmpty(String s) {
        return s != null && !"".equals(s) && !"null".equals(s);
    }

    /**
     * 检测字符串是否为空(null,"","null")
     *
     * @param s
     * @return 为空则返回true，不否则返回false
     */
    public static boolean isEmpty(String s) {
        return s == null || "".equals(s) || "null".equals(s);
    }

    /**
     * 字符串转换为字符串数组
     *
     * @param str        字符串
     * @param splitRegex 分隔符
     * @return
     */
    public static String[] str2StrArray(String str, String splitRegex) {
        if (isEmpty(str)) {
            return null;
        }
        return str.split(splitRegex);
    }

    /**
     * 用默认的分隔符(,)将字符串转换为字符串数组
     *
     * @param str 字符串
     * @return
     */
    public static String[] str2StrArray(String str) {
        return str2StrArray(str, ",\\s*");
    }

    /**
     * 32位唯一字符串
     *
     * @return
     */
    public static String get32UUID() {
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        return uuid;
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，日期转字符串
     *
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String date2Str(Date date) {
        //return date2Str(date, "yyyy-MM-dd HH:mm:ss");
        return date2Str(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，日期转字符串
     *
     * @param
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String date3Str(int a) {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR, a);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        return date2Str(date, "yyyyMMddHH");
    }

    // 获取两个时间相差分钟数
    public static long getTime(String oldTime, String newTime) throws ParseException {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long NTime = df.parse(newTime).getTime();
        //从对象中拿到时间
        long OTime = df.parse(oldTime).getTime();
        long diff = (NTime - OTime) / 1000 / 60;
        return diff;
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，字符串转日期
     *
     * @param date
     * @return
     */
    public static Date str2Date(String date) {
        if (notEmpty(date)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            try {
                return sdf.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return new Date();
        } else {
            return null;
        }
    }

    /**
     * 按照参数format的格式，日期转字符串
     *
     * @param date
     * @param format
     * @return
     */
    public static String date2Str(Date date, String format) {
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        } else {
            return "";
        }
    }

    /**
     * 把时间根据时、分、秒转换为时间段
     *
     * @param StrDate
     */
    public static String getTimes(String StrDate) {
        String resultTimes = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now;
        try {
            now = new Date();
            Date date = df.parse(StrDate);
            long times = now.getTime() - date.getTime();
            long day = times / (24 * 60 * 60 * 1000);
            long hour = (times / (60 * 60 * 1000) - day * 24);
            long min = ((times / (60 * 1000)) - day * 24 * 60 - hour * 60);
            long sec = (times / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

            StringBuffer sb = new StringBuffer();
            if (hour > 0) {
                sb.append(hour + "小时前");
            } else if (min > 0) {
                sb.append(min + "分钟前");
            } else {
                sb.append(sec + "秒前");
            }
            resultTimes = sb.toString();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return resultTimes;
    }


    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 验证手机号码
     *
     * @param
     * @return
     */
    public static boolean checkMobileNumber(String mobileNumber) {
        boolean flag = false;
        try {
            Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
            Matcher matcher = regex.matcher(mobileNumber);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public static String getMonth() {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);//获取系统的年
//		System.out.println(year);

        int month = c.get(Calendar.MONTH) + 1;//获取月份

        return month + "月";
    }


}
